package app.sb.jly.com.ji_liang_yuan.activitys.ac;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.lzy.okgo.OkGo;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import app.sb.jly.com.ji_liang_yuan.R;
import app.sb.jly.com.ji_liang_yuan.activitys.application.BaseApplication;
import app.sb.jly.com.ji_liang_yuan.activitys.commons.CommonUtils;
import app.sb.jly.com.ji_liang_yuan.activitys.commons.Constants;
import app.sb.jly.com.ji_liang_yuan.activitys.commons.DateUtil;
import app.sb.jly.com.ji_liang_yuan.activitys.commons.PDALogUtils;
import app.sb.jly.com.ji_liang_yuan.activitys.commons.SharedPreferencesUtils;
import app.sb.jly.com.ji_liang_yuan.activitys.commons.UtilsLog;
import app.sb.jly.com.ji_liang_yuan.activitys.model.LoginModel;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import pub.devrel.easypermissions.EasyPermissions;


/**
 * @Description: 新版的登录
 */
public class LoginActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks {
    int TYPE_POP = 0;//popuwindow 0：检测模式   1：账号
    @BindView(R.id.imageView)
    ImageView imageView;
    @BindView(R.id.textView)
    TextView textView;
    @BindView(R.id.ac_login_pwd)
    EditText acLoginPwd;
    @BindView(R.id.ac_login_btn_set)
    Button acLoginBtnSet;
    @BindView(R.id.ac_login_view_m)
    TextView acLoginViewM;
    @BindView(R.id.ac_login_btn_login)
    Button acLoginBtnLogin;


    BaseApplication baseApplication;
    @BindView(R.id.ac_login_name)
    EditText acLoginName;
    @BindView(R.id.ac_login_checkBox)
    CheckBox acLoginCheckBox;

    private LoginActivity instances = null;
    public static String[] permissionArray = new String[]{
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_SETTINGS,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.INTERNET,
            Manifest.permission.CAMERA,
            Manifest.permission.READ_CALENDAR,
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        instances = LoginActivity.this;


        baseApplication = BaseApplication.getSelf();
//        String msg = "=======PDA-LOG=====" + "\n" + "移动检测系统版本号::::" +
//                CommonUtils.getVersionName(instances) + "\n" +
//                instances.getResources().getString(R.string.setting_content);
//        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, msg.getBytes());
//

        if (EasyPermissions.hasPermissions(this, permissionArray)) {//检查是否获取该权限
            UtilsLog.e("zzl=已获取权限");
        } else {
            UtilsLog.e("zzl=meiyou===权限");
            EasyPermissions.requestPermissions(this, "必要的权限", 0, permissionArray);
        }


//
//        initUserList();
        String str0 = "", str1 = "";
        str0 = CommonUtils.getIMEI(this, 0);
        str1 = CommonUtils.getIMEI(this, 1);
        UtilsLog.e("手机IMEI---1---" + str0);
        UtilsLog.e("手机IMEI---2---" + str1);

//        UtilsLog.e("获得指定日期的前一天===" + DateUtil.getNowDate(364));
//        UtilsLog.e("获得指定日期的前一月===" + DateUtil.getSpecifiedMonthBefore(DateUtil.getTodayDate()));
        UtilsLog.e("11111===" + DateUtil.getTodayDate_add_one_year(2023, 1, 6));
        UtilsLog.e("11111===" + DateUtil.getTodayDate_add_one_year(2023, 01, 06));
        UtilsLog.e("11111===" + DateUtil.getTodayDate_add_one_year(2023, 01, 01));
        UtilsLog.e("当前日期===" + DateUtil.getTodayDate2());
        UtilsLog.e("当前日期-加一年--减一天===" + DateUtil.getTodayDate_add_one_year());

        if (SharedPreferencesUtils.getCheckbox(instances)) {
            acLoginCheckBox.setChecked(true);
            LoginModel model = SharedPreferencesUtils.getRemeber_name_pwd(instances);
            if (model != null) {
                acLoginName.setText(model.getName());
                acLoginPwd.setText(model.getPwd());
            }
        } else {
            acLoginCheckBox.setChecked(false);
        }


        acLoginCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                acLoginCheckBox.setChecked(isChecked);
                if (isChecked) {
                    remeber_name_pwd();
                } else {
                    SharedPreferencesUtils.setCheckbox(instances, false);
                }
            }
        });


//        UtilsLog.e("111111111111");
//        setTxtContents("济南");
//        UtilsLog.e("22222222222");


    }


    void setTxtContents(String fileName) {
        String str = "";
        for (int i = 0; i < Constants.contents.length; i++) {
            str += Constants.contents[i] + "\r\n";
        }
        UtilsLog.e(str);
//        String logStrf = "\n" + "-------11111111111111----2222222222222---" + "\n";
        PDALogUtils.createTxtFile(fileName, str.getBytes(), this);
    }

    void remeber_name_pwd() {
        SharedPreferencesUtils.setCheckbox(instances, true);
        String UserID = acLoginName.getText().toString().trim();
        String pwd = acLoginPwd.getText().toString().trim();
        LoginModel model = new LoginModel();
        model.setName(UserID);
        model.setPwd(pwd);
        SharedPreferencesUtils.setRemeber_name_pwd(instances, model);
    }

    void initUserList() {
//        WaitDialog.show(instances, "加载中...");
//        Handler handler = new Handler();
//        handler.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                WaitDialog.dismiss();
//            }
//        }, 1500);//后执行Runnable中的run方法

//        PDALogUtils.checkPhotoSetting();
    }


    @OnClick({R.id.imageView, R.id.ac_login_btn_set,
            R.id.ac_login_btn_login})
    public void onViewClicked(View view) {
        {
            switch (view.getId()) {
                //设置
                case R.id.ac_login_btn_set:
//                    instances.finish();
//                    Intent intent = new Intent(LoginActivity.this, SettingActivity.class);
//                    startActivity(intent);
//                this.overridePendingTransition(R.anim.push_left_in,R.anim.push_left_out);
                    break;
                //登录
                case R.id.ac_login_btn_login:
                    String UserID = acLoginName.getText().toString().trim();
                    String pwd = acLoginPwd.getText().toString().trim();
                    UtilsLog.e("UserID==" + UserID);
                    UtilsLog.e("pwd==" + pwd);
                    Map<String, String> userMap = new HashMap<String, String>();
                    userMap.put("马堃", "ma");
                    userMap.put("申东滨", "shen");
                    userMap.put("潘寿虎", "pan");
                    userMap.put("倪俊国", "ni");
                    userMap.put("王述诚","wang");
                    userMap.put("张凯", "zhang");
                    userMap.put("王文龙", "wang");
//                    userMap.put("1", "1");
//                    userMap.keySet().stream().filter(key -> key.equals(UserID) && userMap.get(key).equals(pwd)).forEach(key -> {
//                        remeber_name_pwd();
//                        Intent intent3 = new Intent(LoginActivity.this, MainActivity.class);
//                        startActivity(intent3);
//                        finish();
//                    });
                    if (!TextUtils.isEmpty(UserID) && !TextUtils.isEmpty(pwd)) {
                        for (String key : userMap.keySet()) {
                            if (!key.equals(UserID)) {
                                continue;
                            }
                            if (key.equals(UserID) && userMap.get(key).equals(pwd)) {
                                remeber_name_pwd();
                                Intent intent3 = new Intent(LoginActivity.this, MainActivity.class);
                                startActivity(intent3);
                                finish();
                                break;
                            } else {
                                Toast.makeText(instances, "用户名或密码错误", Toast.LENGTH_LONG).show();
                            }
                        }
                        if (!userMap.containsKey(UserID)){
                            Toast.makeText(instances,"不存在此用户",Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(instances, "用户名或密码不能为空", Toast.LENGTH_LONG).show();
                    }
                    break;
                case R.id.imageView:
//                    Intent intent3 = new Intent(LoginActivity.this, DaiJianCarsActivity.class);
//                    Intent intent3 = new Intent(LoginActivity.this, OnlineActivity.class);
//                    startActivity(intent3);
                    break;
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
//        WaitDialog.show(instances, "加载中...");
////        Handler handler = new Handler();
////        handler.postDelayed(new Runnable() {
////            @Override
////            public void run() {
////                WaitDialog.dismiss();
////            }
////        }, 1500);//后执行Runnable中的run方法
//        PDALogUtils.checkPhotoSetting();
//        if (!TextUtils.isEmpty(SharedPreferencesUtils.getIP(instances)) &&
//                !TextUtils.isEmpty
//                (SharedPreferencesUtils.getFileIP(instances))) {
//            if (CommonUtils.isNetworkConnected(instances)) {
//                getDataUsersList();
//                //获取所有人工检验项目接口
//                getGET_ALL_ITEMList();
//            } else {
//                Toast.makeText(instances, getResources().getString(R.string.network_error), Toast
//                        .LENGTH_LONG).show();
//            }
//        } else {
//            Toast.makeText(instances, "请设置IP与端口号", Toast.LENGTH_LONG).show();
//        }
        initUserList();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        String logStrf = "\n" + "onDestroy-----登陆-------" + "\n";
        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStrf.getBytes());
        OkGo.getInstance().cancelTag(this);
        instances = null;
    }


    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        UtilsLog.e("onPermissionsGranted----请求拍照权限成功===");
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        UtilsLog.e("onPermissionsDenied----请求拍照权限失败===");
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // 将结果转发给 EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
        Log.e("tag", "onRequestPermissionsResult:" + "== requestCode:" + requestCode +
                "===permissions==" + permissions.length +
                "===grantResults==" + grantResults.length);
    }
}